<template>
    <div class="app-container">
      <el-form :model="queryParams" ref="queryForm" :inline="true">
        <el-form-item label="学号" prop="studentId">
          <el-input
            v-model="queryParams.studentId"
            placeholder="请输入学号"
            clearable
            size="small"
            style="width: 240px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="学生姓名" prop="studentName">
          <el-input
            v-model="queryParams.studentName"
            placeholder="请输入学生姓名"
            clearable
            size="small"
            style="width: 240px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="handleQuery"
            >搜索</el-button
          >
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
            >重置</el-button
          >
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            >新增通话额度</el-button
          >
        </el-col>
        <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-upload2"
          size="mini"
          @click="importData"
          >批量导入通话额度</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button type="danger" icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          >删除</el-button>
      </el-col>
      </el-row>
  
      <el-table v-loading="loading" :data="dataList"  @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="id" align="center" v-if="false" />
        <el-table-column label="学号" prop="studentId" align="center" />
        <el-table-column label="学生姓名" prop="studentName" align="center" />
        <el-table-column label="学生班级" prop="studentClass" align="center" />
        <el-table-column label="通话额度" prop="studentCallQuota" align="center" />
        <el-table-column label="剩余时长" prop="remainingDuration" align="center" />
        <el-table-column label="创建人" prop="createBy" align="center" />
        <el-table-column label="创建时间" prop="createTime" align="center" >
            <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
        </el-table-column>
        <el-table-column label="修改人" prop="modifyBy" align="center" />
        <el-table-column label="修改时间" prop="modifyTime" align="center" >
            <template slot-scope="scope">
            <span>{{ parseTime(scope.row.modifyTime) }}</span>
            </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <!-- <el-button
              size="mini"
              circle
              type="success"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
            /> -->
            <el-button
              size="mini"
              circle
              type="success"
              icon="el-icon-circle-plus"
              @click="handleUpdate(scope.row)"
            />
            <el-button
              size="mini"
              circle
              type="danger"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
            />
          </template>
        </el-table-column>
      </el-table>
  
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />

      <el-dialog :title="title" :visible.sync="dialogVisible" width="500px" :before-close="handleClose">
        <el-form
          :model="formData"
          ref="formData"
          :rules="rules"
          label-width="120px"
        >
        <el-form-item label="学生班级" prop="classId" >
            <el-select
              v-model="formData.classId"
              clearable
              filterable
              @change="getStudentList"
              placeholder="请选择"
              style="width: 100%"
            >
              <el-option
                v-for="item in classList"
                :key="item.id"
                :label="item.className"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="学生姓名" prop="studentId" >
            <el-select
              v-model="formData.studentId"
              clearable
              filterable
              multiple
              collapse-tags
              style="width: 100%"
              value-key="studentId"
            >
              <el-option
                v-for="item in studentList"
                :key="item.studentId"
                :label="item.name"
                :value="item"
              >
              </el-option>
            </el-select>
          </el-form-item>
          
          
          <el-form-item label="通话额度" prop="studentCallQuota" >
            <el-input
              style="width: 100%"
              v-model="formData.studentCallQuota"
              placeholder="请输入通话额度,单位为秒"
            >
            </el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="handleSumit">提 交</el-button>
          <el-button @click="handleClose">取 消</el-button>
        </div>
      </el-dialog>

      <el-dialog :title="editTitle" :visible.sync="editDialogVisible" width="500px" :before-close="editHandleClose">
        <el-form
          :model="editFormData"
          ref="editFormData"
          label-width="120px"
        >
        <el-form-item label="学生班级" prop="classId" >
            <template>
            <span>{{ editFormData.studentClass }}</span>
            </template>
          </el-form-item>
          <el-form-item label="学生姓名" prop="studentId" >
            <template>
            <span>{{ editFormData.studentName }}</span>
            </template>
          </el-form-item>
          
          
          <el-form-item label="剩余通话时长" prop="remainingDuration" >
            <el-input
              style="width: 100%"
              v-model="editFormData.quotaSecond"
              placeholder="请输入剩余通话时长,单位为秒"
            >
            </el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="editHandleSumit">提 交</el-button>
          <el-button @click="editHandleClose">取 消</el-button>
        </div>
      </el-dialog>

      <el-dialog title="导入学生通话额度" :visible.sync="importVisible" width="400px" >
        <el-upload v-loading="importLoading"
          class="upload-demo"
          drag
          :action="upload.url"
          :headers="upload.headers"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
          :file-list="fileList"
          >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip" slot="tip"><el-link type="primary" @click="importTemplateFile">模板下载</el-link></div>
        </el-upload>
      </el-dialog>
    </div>
  </template>
  
  <script>
  import { pageList, deleteInfo, addStudentCallQuotaInfo, importTemplate } from "@/api/publicPhone/callQuota";
  import { findAllSchoolClass} from "@/api/studentInfo/infoMaintenance/index";
  import { originalData} from "@/api/studentInfo/infoMaintenance/index";
  import { getToken } from '@/utils/auth'

  export default {
    name: "callQuota",
  
    data() {
      return {
        upload:{
            url:process.env.VUE_APP_BASE_API + '/student/call/importData',
            headers: {Authorization:"Bearer " + getToken()},
        },
        // 遮罩层
        loading: false,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        //打开对话框
        dialogVisible: false,
        // 总条数
        total: 0,
        // 弹出层标题
        title: "",
        editTitle: "",
        editDialogVisible: false,
        // 表格数据
        dataList: [],
        //班级信息
        classList:[],
        //学生信息
        studentList:[],
        fileList:[],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          studentId: undefined,
          studentName: undefined
        },
        formData: {

        },
        editFormData: {

        },
        rules: {
            classId:[{ required: true, message: "班级名称不能为空", trigger: "blur" }],
            studentId:[{ required: true, message: "学生名称不能为空", trigger: "blur" }],
            studentCallQuota:[{ required: true, message: "请输入通话额度", trigger: "blur" }],
        },
        importVisible:false,
        importLoading:false
      };
    },
  
    created() {
      this.getList();
      this.getClassList();

    },
  
    methods: {
      getList() {
        this.loading = true;
        pageList(this.queryParams)
          .then((response) => {
            this.dataList = response.data.list;
            this.total = response.data.total;
            this.loading = false;
          })
          .catch((res) => {
            this.loading = false;
          });
      },

        /** 下载模板操作 */
        importTemplateFile() {
          importTemplate().then(response => {
            this.fileDownload(response.data, "学生通话额度导入模板.xlsx");
          });
        },

      importData(){
            //打开导入页面
            this.importVisible = true
            this.fileList = []
        },
  
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
      getStudentList(val) {
            const studentParam = {
                classId:val,
                pageNum: 1,
                pageSize:1000
            } 
            originalData(studentParam).then((res) => {
                this.studentList = res.data.list;
                
            });
        },
      getClassList(){
            findAllSchoolClass().then(resp=>{
                this.classList = resp.data
            })
        },
      /** 重置表单 */
      reset() {
        this.appVersionForm = {
          appType: undefined,
          versionName: undefined,
          versionNo: undefined,
          downloadAddr: undefined,
          description: undefined,
        };
        this.resetForm("appVersionForm");
      },
  
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
  
      /** 重置查询 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      handleAdd() {
        this.dialogVisible = true;
        this.reset(this.formData);
        this.title = "新增通话额度信息";
      },

     /** 关闭弹窗 */
      handleClose(done) {
        this.dialogVisible = false;
      },

    /** 关闭弹窗 */
      editHandleClose(done) {
        this.editDialogVisible = false;
      },
  
      handleSumit() {
        this.formData.className = this.getClassName(this.classList,this.formData.classId)

        const formDataList = [];
        if(this.formData.studentId.length > 0) {
            for(let i = 0; i < this.formData.studentId.length; i++) {
                const tempFormDate = {
                    studentId: this.formData.studentId[i].studentId,
                    studentName: this.formData.studentId[i].name,
                    studentClass: this.formData.className,
                    classId: this.formData.classId,
                    studentCallQuota: this.formData.studentCallQuota
                };
                formDataList.push(tempFormDate);
            }

        }

        this.$refs["formData"].validate((valid) => {
          if (valid) {
            
            addStudentCallQuotaInfo(formDataList).then((result) => {
              this.$message({ message: "提交成功", type: "success" });
              this.dialogVisible = false;
              this.getList();
              this.resetForm("formData");
            });
          }
        });
      },

      editHandleSumit() {
        const formDataList = [];  
        console.log(this.editFormData)
        formDataList.push(this.editFormData);          
            addStudentCallQuotaInfo(formDataList).then((result) => {
              this.$message({ message: "修改成功", type: "success" });
              this.editDialogVisible = false;
              this.getList();
              this.resetForm("editFormData");
            });
      },
      getClassName(list,id){
        for(let i=0;i<list.length;i++){
            if(list[i].id==id){
                return list[i].className
            }
        }
      },
      getStudentName(list,studentId){
        for(let i=0;i<list.length;i++){
            if(list[i].studentId==studentId){
                return list[i].name
            }
        }
      },

      handleAvatarSuccess(res, file){
            if(res.code==200){
                this.$message({ message: '导入成功', type: 'success'});
                this.importLoading = false
                this.importVisible = false
                this.getList()
            }else{
                this.$message.error(res.message);
                this.importLoading = false
            }
            this.fileList=[]
        
        },
        beforeAvatarUpload(file){
            this.importLoading = true
            console.log(file.name.lastIndexOf('.xlsx'))
            if(file.name.lastIndexOf('.xlsx')<0 && file.name.lastIndexOf('.XLSX')<0){
                this.$message({
                message: '上传文件只能是.xlsx文件',
                type: 'warning'
                });
                return false
            }
            console.log(file,'beforefile')
        },

      handleUpdate(row){
          this.editDialogVisible = true;
          this.editFormData = row
          this.editTitle = "增加剩余通话时长";

        },
    /** 删除配置 */
        handleDelete(row) {
        const ids = row.id || this.ids;
        console.log(ids)
        this.$confirm(
          '是否确认删除数据项?',
          "警告",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        )
          .then(function () {
            return deleteInfo(ids);
          })
          .then(() => {
            this.getList();
            this.msgSuccess("删除成功");
          })
          .catch(function () {});
      },  

    },
  };
  </script>